<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col :span="8">
          <el-input
            v-model.trim="query"
            suffix-icon="el-icon-search"
            placeholder="请输入查询内容"
            clearable
            @keyup.enter.native="searchFn"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" class="searchBtn" @click="searchFn"
            >搜索</el-button
          >

          <el-button type="success" @click="addFn" class="searchBtn"
            >新增用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="id" label="ID" width="180"> </el-table-column>
        <el-table-column prop="username" label="Username" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="联系方式"> </el-table-column>

        <el-table-column prop="email" label="邮箱"> </el-table-column>

        <el-table-column prop="role_name" label="角色"> </el-table-column>

        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.column }} -- {{ scope.row }} == {{ scope.$index }} -->
            <el-switch
              v-model="scope.row.mg_state"
              :active-color="'#13ce66'"
              :inactive-color="'#ff4949'"
              @change="updateUserState(scope.row.id, scope.row.mg_state)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editFn(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.id)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="角色分配"
              placement="top-start"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page.sync="pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 新增弹框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addFlag"
      width="50%"
      :show-close="false"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetAddFormFn('addFormRef')">取 消</el-button>
        <el-button type="primary" @click="addSaveFn('addFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog
      :title="'编辑用户 - [ID:' + editForm.editId + ']'"
      :visible.sync="editFlag"
      width="50%"
      :show-close="false"
    >
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditFormFn('editUserFormRef')">取 消</el-button>
        <el-button type="primary" @click="editSaveFn('editUserFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="eidtRoletFlag" width="50%">
      <el-form :model="userInfo" ref="userInfoRef" label-width="100px">
        <el-form-item label="当前用户:">
          <strong> {{ userInfo.username }} </strong>
        </el-form-item>
        <el-form-item label="当前角色:">
          <strong>
            {{ userInfo.role_name }}
          </strong>
        </el-form-item>

        <el-form-item label="分配新角色">
          <el-select v-model="selectedRoleId" placeholder="请选择角色">
            <!-- :label 显示文本，:value 选中值 -->
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetRoleForm">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsersAPI,
  updateUserStateAPI,
  addSaveAPI,
  editSaveAPI,
  deleteUserAPI,
  getRolesAPI,
  setUserRoleAPI
} from '@/api'
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1(3|4|5|6|7|8)\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }

    return {
      query: '',
      pagenum: 1,
      pagesize: 10,
      userList: [],
      total: 0,
      addFlag: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editFlag: false,
      editForm: {
        editId: 0,
        username: '',
        email: '',
        mobile: ''
      },

      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }
        ]
      },
      eidtRoletFlag: false,
      // 保存正在操作的那个用户信息
      userInfo: {},
      // 保存所有的角色信息
      rolesList: [],
      // 保存用户选中的角色id
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
    this.getRole()
  },
  methods: {
    // 单条删除
    async removeById(id) {
      const result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      if (result === 'cancal') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }

      const { data: res } = await deleteUserAPI(id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },

    // 条件查询
    searchFn() {
      if (this.query.length === 0) return
      this.getUserList()
    },

    async getUserList() {
      const { data: res } = await getUsersAPI({
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      })
      if (res.meta.status === 200) {
        // console.log(res.data)
        this.userList = res.data.users
        this.total = res.data.total
      } else {
        this.$message.error('获取用户列表出现异常')
      }
    },
    // 修改当前页码
    handleCurrentChange(val) {
      this.pagenum = val
      this.getUserList()
    },
    // 修改页码容量
    handleSizeChange(val) {
      //   console.log(val)；
      this.pagesize = val
      this.getUserList()
    },
    // 修改状态
    async updateUserState(uid, type) {
      //   console.log(uid, type)
      const { data: res } = await updateUserStateAPI(uid, String(type))
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.$message.success({
        showClose: true,
        message: res.meta.msg
      })
    },
    // 打开新增弹框
    addFn() {
      this.addFlag = true
    },
    // 新增保存
    addSaveFn(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const { data: res } = await addSaveAPI({
          ...this.addForm
        })
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)

        this.$message({
          message: res.meta.msg,
          type: 'success'
        })
        this.resetAddFormFn(formName)
        this.getUserList()
      })
    },
    resetAddFormFn(formName) {
      // 表单按钮重置k
      this.$refs[formName].resetFields()
      this.addFlag = false
    },
    // 点击编辑按钮
    editFn(row) {
      // console.log(row)
      this.editFlag = true
      this.editForm.editId = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
    },
    // 编辑保存
    editSaveFn(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const { data: res } = await editSaveAPI({
          ...this.editForm
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        this.$message({
          message: res.meta.msg,
          type: 'success'
        })
        this.resetEditFormFn(formName)
        this.getUserList()
      })
    },
    // 重置编辑
    resetEditFormFn(formName) {
      this.editFlag = false
      // this.$refs[formName].resetFields(); ==> 只是把数据重置到绑定模型的数据上
      this.editForm.editId = -1
      this.editForm.username = ''
      this.editForm.email = ''
      this.editForm.mobile = ''
    },
    async getRole() {
      const { data: res } = await getRolesAPI()
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 打开权限分配对话框
    async showSetRoleDialog(row) {
      // 保存起来以供后续使用
      this.userInfo = row
      // console.log(this.userInfo)
      // 展示分配角色对话框
      this.eidtRoletFlag = true
    },
    // 分配角色保存
    async saveRole() {
      // console.log(this.selectedRoleId)
      if (this.selectedRoleId === '') {
        return this.$message.error('请选择 需要分配的角色')
      }
      const { data: res } = await setUserRoleAPI({
        id: this.userInfo.id,
        rid: this.selectedRoleId
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.$message.success(res.meta.msg)
      this.eidtRoletFlag = false
      this.getUserList()
    },
    // 重置角色分配表单
    resetRoleForm() {
      this.eidtRoletFlag = false
      this.userInfo.username = ''
      this.userInfo.role_name = ''
      this.userInfo.id = -1
      this.selectedRoleId = ''
    }
  }
}
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.searchBtn {
  margin-left: 10px;
}
</style>
